<template>
  <div class="login-container">
    <el-card class="login-card">
      <el-form ref="form" :model="form" label-width="80px" class="login-form">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="form.verifyCode" placeholder="请输入验证码" style="width: 120px; margin-right: 10px;"></el-input>
          <span class="verify-code-img">{{ verifyCode }}</span>
          <el-button icon="el-icon-refresh" @click="refreshVerifyCode"></el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onLogin">登录</el-button>
          <el-button type="text" style="float: right;" @click="forgetPassword">忘记密码？</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from "@/api/user";

export default {
  name: "LoginView",
  data() {
    return {
      form: {
        username: "张三",
        password: "123456",
        verifyCode: "VBFJ"
      },
      verifyCode: "VBFJ" // 示例验证码，实际应从后端获取或生成
    };
  },
  methods: {
    onLogin() {
      console.log("登录", this.form);
      login(this.form).then((res) => {
        console.log("返回登录信息", res);
        if (res.code !== "200" || this.verifyCode !== this.form.verifyCode) {
          // this.$message.error("用户名、密码或验证码错误");
          this.$message.error(res.msg);
        } else {
          this.$message.success("登录成功");
          // 保存用户信息到vuex
          this.$store.commit('saveUserInfo',res.data)
          // 登录成功后，跳转到后台管理页面
          this.$router.push("admin");
        }
      }).catch(err => {
        this.$message.error('服务器异常,请联系管理员');
      });
    },
    refreshVerifyCode() {
      // 实际开发中，这里应调用接口获取新的验证码
      // 示例：生成随机验证码，这里简单替换
      const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      let newCode = "";
      for (let i = 0; i < 4; i++) {
        newCode += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.verifyCode = newCode;
    },
    forgetPassword() {
      this.$message.info("忘记密码功能待开发");
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(to bottom right, #edc9b3, #d1e2ff);
}
.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.login-form {
  padding: 20px 40px 40px;
}
.verify-code-img {
  display: inline-block;
  width: 100px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
  font-weight: bold;
  letter-spacing: 2px;
}
.login-btn {
  width: 100%;
}
</style>